﻿using System;
using Samurai.Infrastructure;
using System.Net;

namespace Samurai.MovieIndustry
{
    public class MovieDirector : IMovieDirector
    {
        public Movie Generate(CandidateMovie candidateMovie)
        {
            var service = ResolveMovieService();

            try
            {
                var movieInfo = service.GetInfo(candidateMovie.Name);

                return new Movie
                           {
                               Path = candidateMovie.Path,
                               Rating = movieInfo.Rating,
                               Title = movieInfo.Title,
                               Year = movieInfo.Year,
                               Url = movieInfo.Url,
                               Genres = movieInfo.Genres,
                               Error = (movieInfo.Error ?? string.Empty),
                               ImageUrl = movieInfo.ImageUrl,
                               Image = ImageProcessor.DownloadImage(movieInfo.ImageUrl)
                           };
            }

            catch (WebException)
            {
                throw;
            }

            catch (Exception ex)
            {
                return new Movie { Error = Constants.ErrorMovieCreation };
            }

        }

        private static IMovieService ResolveMovieService()
        {
            return new ImdbApiMovieService();
        }
    }

    public static class ImageProcessor
    {
        public static byte[] DownloadImage(string _URL)
        {
            var webClient = new WebClient();
            byte[] imageBytes = webClient.DownloadData(_URL);

            return imageBytes;
        }
    }
}
